﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using EshubaAnalyser;

namespace Common
{
    [Serializable]
    public class EshubaCache : ISerializable
    {
        private static EshubaCache _instance;
        public static EshubaCache Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    if (_instance == null) _instance = Read();
                    if (_instance == null) _instance = new EshubaCache();
                }
                return _instance;
            }
        }

        private EshubaCache(SerializationInfo info, StreamingContext context)
        {
            this.MenuCache = info.TryGetValue<Dictionary<Guid, EshubaMenu>>("_menuCache");
            this.BookCache = info.TryGetValue<Dictionary<Guid, EshubaBook>>("_bookCache");
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("_menuCache", MenuCache);
            info.AddValue("_bookCache", BookCache);
        }

        private EshubaCache()
        {

        }

        /// <summary>
        /// 读取一个配置文件
        /// </summary>
        /// <returns></returns>
        private static EshubaCache Read()
        {
            return Serializer.TryDesSerialize<EshubaCache>(ImagePath);
        }

        public static void Save()
        {
            Serializer.TrySerialize(_instance, ImagePath);
        }

        private static readonly object InstanceLock = new object();

        public readonly EshubaMenu MenuTreeCache = new EshubaMenu();
        public readonly Dictionary<Guid, EshubaMenu> MenuCache = new Dictionary<Guid, EshubaMenu>();
        public readonly Dictionary<Guid, EshubaBook> BookCache = new Dictionary<Guid, EshubaBook>();

        private static readonly string ImagePath = AppDomain.CurrentDomain.BaseDirectory + "cache.esb";
    }
}
